"""
日志面板组件，显示播放日志和AI回复日志
"""
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGroupBox, QVBoxLayout, QTextEdit, QCheckBox
from PyQt5.QtCore import Qt

# 导入配置类
from app.config.app_config import AppConfig

class LogPanel(QWidget):
    """
    日志面板组件，显示播放日志和AI回复日志
    """
    
    def __init__(self, parent=None):
        """
        初始化日志面板
        """
        super().__init__(parent)
        
        # 获取配置实例
        self.config = AppConfig.get_instance()
        
        self._init_ui()
    
    def _init_ui(self):
        """
        初始化UI
        """
        # 创建主布局
        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(5)
        
        # 创建播放日志区域
        self._create_playback_log()
        
        # 创建AI回复日志区域
        self._create_ai_log()
        
        # 设置日志区域高度
        self.setMinimumHeight(150)
        self.setMaximumHeight(200)
    
    def _create_playback_log(self):
        """
        创建播放日志区域
        """
        playback_log_group = QGroupBox("播放日志")
        playback_log_layout = QVBoxLayout(playback_log_group)
        
        # 添加调试日志开关
        self.debug_checkbox = QCheckBox("显示Socket数据日志")
        self.debug_checkbox.setChecked(self.config.is_debug_enabled())
        self.debug_checkbox.toggled.connect(self._on_debug_toggled)
        playback_log_layout.addWidget(self.debug_checkbox)
        
        self.playback_log = QTextEdit()
        self.playback_log.setReadOnly(True)
        self.playback_log.setStyleSheet("""
            QTextEdit {
                border: 1px solid #ddd;
                border-radius: 3px;
                background-color: #f9f9f9;
                font-family: "Consolas", "Microsoft YaHei", monospace;
                font-size: 12px;
            }
        """)
        playback_log_layout.addWidget(self.playback_log)
        
        # 设置伸展因子为1，使其占据50%的宽度
        self.layout.addWidget(playback_log_group, 1)
    
    def _create_ai_log(self):
        """
        创建AI回复日志区域
        """
        ai_log_group = QGroupBox("AI回复")
        ai_log_layout = QVBoxLayout(ai_log_group)
        
        self.ai_log = QTextEdit()
        self.ai_log.setReadOnly(True)
        self.ai_log.setStyleSheet("""
            QTextEdit {
                border: 1px solid #ddd;
                border-radius: 3px;
                background-color: #f9f9f9;
                font-family: "Consolas", "Microsoft YaHei", monospace;
                font-size: 12px;
            }
        """)
        ai_log_layout.addWidget(self.ai_log)
        
        # 设置伸展因子为1，使其占据50%的宽度
        self.layout.addWidget(ai_log_group, 1)
    
    def _on_debug_toggled(self, checked):
        """
        处理调试开关状态变化
        
        @param checked: 是否选中
        """
        # 更新配置
        self.config.set_debug_enabled(checked)
    
    def add_playback_log(self, message):
        """
        添加播放日志
        
        @param message: 日志消息
        """
        # 检查是否为用户进入的消息，不显示
        if message.startswith("用户进入:"):
            return
            
        # 检查是否为Socket数据日志
        is_socket_log = message.startswith("收到") or "Socket" in message
        
        # 如果是Socket数据日志且调试模式关闭，则不显示
        if is_socket_log and not self.config.is_debug_enabled():
            return
        
        # 添加日志
        self.playback_log.append(message)
        
        # 限制日志条数
        max_log_entries = self.config.get("ui", "max_log_entries", 100)
        document = self.playback_log.document()
        if document.blockCount() > max_log_entries:
            cursor = self.playback_log.textCursor()
            cursor.movePosition(cursor.Start)
            cursor.movePosition(cursor.Down, cursor.KeepAnchor, document.blockCount() - max_log_entries)
            cursor.removeSelectedText()
    
    def add_ai_log(self, message):
        """
        添加AI回复日志
        
        @param message: 日志消息
        """
        try:
            # 检查消息类型
            if not isinstance(message, str):
                self.ai_log.append(f"[警告] 收到非字符串类型的消息: {type(message)}")
                message = str(message)
            
            # 检查消息长度，避免过长消息导致UI卡顿
            if len(message) > 10000:
                message = message[:10000] + "... [消息过长，已截断]"
            
            # 添加消息到日志
            self.ai_log.append(message)
            
            # 限制日志条数
            max_log_entries = self.config.get("ui", "max_log_entries", 100)
            document = self.ai_log.document()
            if document.blockCount() > max_log_entries:
                cursor = self.ai_log.textCursor()
                cursor.movePosition(cursor.Start)
                cursor.movePosition(cursor.Down, cursor.KeepAnchor, document.blockCount() - max_log_entries)
                cursor.removeSelectedText()
        except Exception as e:
            import traceback
            print(f"添加AI日志时出错: {str(e)}")
            print(traceback.format_exc())
    
    def clear_logs(self):
        """
        清空所有日志
        """
        self.playback_log.clear()
        self.ai_log.clear() 